# -*- coding: utf-8 -*-
import time
import uuid
import hashlib
import base64
import requests  # 需要先使用pip install requests命令安装依赖

from util.config_center import ConfigCenter


class PhoneSender:
    def __init__(self):
        config = ConfigCenter.get_phone_sender_config()
        self._url = config.get("url")
        self._app_key = config.get("app_key")
        self._app_secret = config.get("app_secret")
        self._sender = config.get("sender")
        self._template_id = config.get("template_id")

    def build_wsse_header(self):
        now = time.strftime('%Y-%m-%dT%H:%M:%SZ')  # Created
        nonce = str(uuid.uuid4()).replace('-', '')  # Nonce
        digest = hashlib.sha256((nonce + now + self._app_secret).encode()).hexdigest()
        digest_base64 = base64.b64encode(digest.encode()).decode()  # PasswordDigest
        return 'UsernameToken Username="{}",PasswordDigest="{}",Nonce="{}",Created="{}"'.format(
            self._app_key, digest_base64, nonce, now)

    def send_msg(self, contact, msg):
        """

        :param contact:
        :param msg:
        :return:
        """
        # 请求Headers
        header = {'Authorization': 'WSSE realm="SDP",profile="UsernameToken",type="Appkey"',
                  'X-WSSE': self.build_wsse_header()}
        # 请求Body
        form_data = {'from': self._sender,
                     'to': contact,
                     'templateId': self._template_id,
                     'templateParas': msg,
                     'statusCallback': "",
                     }
        # 为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
        requests.post(self._url, data=form_data, headers=header, verify=False)